<template>
  <layout>
    <!-- <template slot="title">
      <template v-if="!this.isPreview">
        分户补贴明细表
        <a-button type="link" @click="handlerExportExecl">单独导出EXCEL表去打印</a-button>
      </template>
    </template> -->

    <section v-if="!this.isPreview" class="title">
      <p>
        分户补贴明细表
        <a-button type="link" @click="handlerExportMembers"
          >[单独导出EXCEL表去打印后张贴]</a-button
        >
      </p>
      <p>
        {{
          `1、本区（县）${isLarge ? '种粮大户' : '一般农户'}种粮补贴按“${
            PayUnitTypeMap.get(currentFarmland.pay_unit) || '未设置'
          }”和${currentFarmland.pay_price}元/亩计算；2、补贴资金将直接兑付到${
            isLarge ? '大户' : '户主'
          }银行账户；3、欢迎社会各界人士监督。`
        }}
      </p>
    </section>

    <!-- 产品列表 -->
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="(record) => record.member_id"
      :customRow="customTableRow"
      :pagination="false"
      :loading="tableLoading"
      :scroll="{
        x: '100%',
        y: 500,
      }"
      bordered
    >
      <template slot="field1" slot-scope="row, record, index">
        <span v-if="index === 0">{{ row.field1 || 0 }}</span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click="handlerManageFarmLand(row, 1)"
          >{{ row.field1 || 0 }}</a-button
        >
      </template>
      <template slot="field2" slot-scope="row, record, index">
        <span v-if="index === 0">{{ row.field2 || 0 }}</span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click="handlerManageFarmLand(row, 2)"
          >{{ row.field2 || 0 }}</a-button
        >
      </template>
      <template slot="field3" slot-scope="row, record, index">
        <span v-if="index === 0">{{ row.field3 || 0 }}</span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click="handlerManageFarmLand(row, 3)"
          >{{ row.field3 || 0 }}</a-button
        >
      </template>
      <template slot="plant" slot-scope="row, record, index">
        <span v-if="index === 0">{{ row.plant || 0 }}</span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click="handlerPlant(row)"
          >{{ row.plant || 0 }}</a-button
        >
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      showSizeChanger
      :pageSize="pageSize"
      :show-total="showTotal"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>
  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import { State, Mutation, Getter, namespace } from 'vuex-class'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'
import { exportDataHandler } from '@/utils/execl'
import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { publishServices, IPublish } from '@/common/services/publish'
import { userModule } from '@/store/modules/user'
import MemberFarmland from '../../member/grain/Farmland.vue'
import MemberLargeFarmland from '../../member/large-grain/Farmland.vue'
import PublicPlant from './PublicPlant.vue'
import { famerServices, IGrain } from '@/common/services/famer'
import { largeMemberServices } from '@/common/services/largeMember'
import PublicSelectExport from './PublicSelectExport.vue'
import { message } from 'ant-design-vue'
import { PayUnitTypeMap } from '@/common/enum'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
    MemberFarmland,
    MemberLargeFarmland,
    PublicPlant,
    PublicSelectExport,
  },
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  @Prop({
    type: String,
  })
  public currentAreaId!: string
  @Prop({
    type: String,
  })
  public currentPubId!: string
  @Prop({
    type: Object,
  })
  public currentPub!: IPublish

  @Prop({
    type: Boolean,
    default: () => false,
  })
  public isPreview!: boolean
  @Prop({
    type: Boolean,
    default: () => false,
  })
  public isLargeMember!: boolean

  @Prop({
    type: String,
  })
  public showArea!: string

  get isPlant() {
    return userModule.isPlant
  }

  get isLarge() {
    return this.isPlant ? this.isLargeMember : userModule.isLarge
  }

  get PayUnitTypeMap() {
    return PayUnitTypeMap
  }

  public hasTotalRow = true

  public currentFarmland = {
    pay_unit: '',
    pay_price: '',
  }

  public commonParams = {
    s_a_id: '',
    pub_id: '',
    is_big_member: this.isLargeMember || false,
  }

  // 产品列表搜索条件
  public tableSearch = {
    show_area: '',
  }

  // 自定义mode
  public customMode = 'add'

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    {
      title: this.isLarge ? '大户编号' : '农户编号',
      dataIndex: 'member_id',
      key: 'member_id',
      width: 160,
    },
    {
      title: this.isLarge ? '大户名称' : '户主姓名',
      dataIndex: 'member_nam',
      key: 'member_nam',
      width: 120,
    },

    {
      title: this.isLarge ? '种粮地址' : '家庭地址',
      key: 's_a_nam_all',
      dataIndex: 's_a_nam_all',
      width: 200,
    },

    !this.isPlant
      ? {
          title: '实际耕种面积（亩）',
          children: [
            {
              title: '合计',
              key: 'field',
              dataIndex: 'field',
              align: 'right',
              width: 120,
            },
            {
              title: '基础面积',
              key: 'field1',
              scopedSlots: { customRender: 'field1' },
              align: 'right',
              width: 100,
            },
            {
              title: '增加面积',
              key: 'field2',
              scopedSlots: { customRender: 'field2' },
              align: 'right',
              width: 100,
            },
            {
              title: '减少面积',
              key: 'field3',
              scopedSlots: { customRender: 'field3' },
              align: 'right',
              width: 100,
            },
          ],
        }
      : {},
    {
      title: '粮食种植面积(亩)',
      scopedSlots: { customRender: 'plant' },
      key: 'plant',
      align: 'right',
      width: 120,
    },
    {
      title: '补贴面积（亩）',
      dataIndex: 'bt_size',
      key: 'bt_size',
      align: 'right',
      width: 120,
    },
    {
      title: '补贴总金额（元）',
      dataIndex: 'pay_price_total',
      key: 'pay_price_total',
      align: 'right',
      width: 140,
    },

    this.isLarge
      ? {
          title: '法人身份证',
          dataIndex: 'member_law_id',
          key: 'member_law_id',
          width: 160,
        }
      : {
          title: '身份证',
          dataIndex: this.isPlant ? 'member_law_id' : 'member_sfz',
          key: this.isPlant ? 'member_law_id' : 'member_sfz',
          width: 160,
        },
    {
      title: '收款账号',
      dataIndex: 'bank_num',
      key: 'bank_num',
      // scopedSlots: { customRender: 'bank_num' },
      width: 140,
    },
    {
      title: '备注',
      dataIndex: 'readme',
      key: 'readme',
      width: 160,
    },
  ].filter((_) => _.title)

  public tableApi: Record<string, unknown> = {
    list: '',
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    this.commonParams.pub_id = this.currentPubId
    this.tableSearch.show_area = this.showArea
    this.handlerCurrentisPreviewChange()
    this.getData()
  }

  @Watch('isPreview')
  public handlerCurrentisPreviewChange() {
    this.tableApi.list = this.isPreview
      ? publishServices.previewMembers
      : publishServices.getPublishUsers
  }

  public mounted() {}

  public async getData() {
    const res = await this.getTableList()

    // 从列表数据中提取pay_unit | pay_price
    const data = res.data.data[1]
    if (data) {
      this.currentFarmland = {
        pay_unit: data.pay_unit,
        pay_price: data.pay_price,
      }
    }

    // @ts-ignore
    this.tableData = res.data.data.map((item) => {
      return {
        ...item,
        // bank_num: item.bank_num ? ('***' + item.bank_num.slice(-6)) : ''
      }
    })
  }

  // 管理耕地信息
  public handlerManageFarmLand(row: IGrain, mode: number) {
    this.$dialog(
      this.isLarge ? MemberLargeFarmland : MemberFarmland,
      {
        isReadOnly: true,
        currentFieldType: mode,
        currentField: {
          ...row,
          ...(this.isLarge
            ? { big_mb_id: row.member_id }
            : { family_id: row.member_id }),
        },
      },
      {
        width: '70%',
        centered: true,
      }
    )
  }

  // 粮食种植面积（亩)
  public async handlerPlant(row: IGrain) {
    const { data } = this.isLarge
      ? await largeMemberServices.getLargeMemberPlants({
          big_mb_id: row.member_id,
          s_a_id: this.currentPub.s_a_id,
        })
      : await famerServices.getMemberPlant({
          family_id: row.member_id,
          s_a_id: this.currentPub.s_a_id,
        })
    this.$dialog(
      PublicPlant,
      {
        plant: data || {},
      },
      {
        title: '粮食种植面积',
        width: '400px',
        bodyStyle: {
          maxHeight: '80vh',
        },
        centered: true,
        maskClosable: false,
        footer: null,
      }
    )
  }

  public handlerExportMembers() {
    const currentPubId = this.currentPubId
    this.$dialog(
      PublicSelectExport,
      {},
      {
        title: '请选择导出字段',
        width: '600px',
        bodyStyle: {
          maxHeight: '80vh',
        },
        centered: true,
        maskClosable: false,
        on: {
          async ok() {
            // @ts-ignore
            const fields = this.$refs._component.currentSelected
            // @ts-ignore
            const type = this.$refs._component.currentType as string
            if (!fields.length) {
              message.error('请选择导出字段')
              return false
            }
            const _ = await publishServices.exportPublishMemberExecl({
              pub_id: currentPubId,
              exportExcelMode: type,
              keys: fields,
            })
            // @ts-ignore
            const filename = _.headers['content-disposition']
              .replace(/(.*)(?=filename=)/g, '')
              .replace('filename=', '')
            const data = _.data
            const url = window.URL.createObjectURL(data)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', decodeURI(filename))
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            return true
          },
        },
      }
    )
  }

  public handlerExportExecl() {
    publishServices
      .getPublishUsers({
        pub_id: this.currentPubId,
        page: 1,
        pageSize: 99999,
      })
      .then((_) => {
        // @ts-ignore
        const data = _.data.data.slice(1).map((item) => {
          return {
            ...item,
            // bank_num: item.bank_num ? ('***' + item.bank_num.slice(-6)) : ''
          }
        })
        // 获取execl-key
        const fields: Record<string, string> = {
          member_id: this.isLarge ? '大户编号' : '农户编号',
          member_nam: this.isLarge ? '大户名称' : '户主姓名',
          s_a_nam_all: this.isLarge ? '种粮地址' : '家庭地址',
          field: '确权面积合计',
          field1: '确权面积',
          field2: '增加面积',
          field3: '减少面积',
          plant: '粮食种植面积（亩）',
          bt_size: '补贴面积（亩）',
          pay_price_total: '补贴总金额（元）',
          bank_num: '收款账户',
        }
        // @ts-ignore
        exportDataHandler(
          data,
          fields,
          this.currentPub.s_a_nam_all + '-分户补贴明细表' + '.xlsx'
        )
        this.$message.success('下载成功')
      })
  }
}
</script>

<style scoped lang="less">
.title {
  padding-bottom: 10px;
  p:nth-child(1) {
    font-weight: bold;
  }
}
</style>
